package cn.funeralobjects.util.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 方便用于管理的全局线程工厂
 *
 * @author FuneralObjects
 * Create date: 2020/4/16 2:31 PM
 */
public class GlobalTreadFactory implements ThreadFactory {

    /**
     * 线程序列
     */
    private static AtomicLong THREAD_INDEX = new AtomicLong(0L);
    /**
     * 线程前缀
     */
    private static final String THREAD_NAME_PREFIX = "f-global-thread";
    /**
     * 线程组
     */
    private static ThreadGroup GLOBAL_GROUP = new ThreadGroup(THREAD_NAME_PREFIX);

    private GlobalTreadFactory() {

    }

    private static GlobalTreadFactory THEAD_FACTORY = new GlobalTreadFactory();

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(GLOBAL_GROUP, r);
        t.setName(THREAD_NAME_PREFIX + "-[" + THREAD_INDEX.incrementAndGet() + "]");
        return t;
    }

    public static GlobalTreadFactory getInstance() {
        return THEAD_FACTORY;
    }

    /**
     * 查看所有执行数量
     *
     * @return 线程数
     */
    public static int activeCount() {
        return GLOBAL_GROUP.activeCount();
    }

    /**
     * 中断所有线程
     */
    public static void interrupt() {
        GLOBAL_GROUP.interrupt();
    }

    /**
     * 提供一个子线程组
     *
     * @param name 子线程组名称
     * @return 子线程
     */
    public static ThreadGroup registerSubThreadGroup(String name) {
        return new ThreadGroup(GLOBAL_GROUP, name);
    }

    public static String getName() {
        return THREAD_NAME_PREFIX;
    }

    public static long getCurrentIndex() {
        return THREAD_INDEX.get();
    }
}
